package org.dromara.pay.jobhandler;

import cn.hutool.core.util.ObjectUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.business.service.BusinessConfigService;
import org.dromara.pay.service.TopUpService;
import org.hibernate.validator.internal.util.stereotypes.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledExecutorService;


/**
 * 定时任务
 *
 * @author zlj
 * @since 2023/8/10
 */
@Slf4j
@Component
@EnableScheduling
public class WxOrderHandler {

//    @Resource
//    private OrderService orderService;
    @Resource
    private BusinessConfigService configService;
    @Resource
    @Lazy
    private TopUpService topUpService;
    @Resource
    private ScheduledExecutorService scheduledExecutorService;

    /**
     * 更新微信订单收货信息
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void updateOrder() {
        String isWxOrder = configService.queryValueByKey("is_wx_order");
        if (ObjectUtil.notEqual(isWxOrder, "1")) {
            return;
        }
        log.info("=========================开始更新微信订单收货信息=========================");
        Integer num = 0;
//        List<Order> list = orderService.lambdaQuery().eq(Order::getStatus, "2").list();
//        if (CollectionUtil.isNotEmpty(list)) {
//            List<Long> ids = StreamUtils.toList(list, Order::getOrderId);
//            List<TopUp> topUpList = topUpService.lambdaQuery().select(TopUp::getTopUpId, TopUp::getTransactionId, TopUp::getOrderJson)
//                .in(TopUp::getOrderJson, ids).list();
//            for (TopUp topUp : topUpList) {
//                Boolean flag = WxOrderUtil.getOrderStatus(topUp.getTransactionId());
//                if (flag) {
//                    num++;
//                    for (Order order : list) {
//                        if (String.valueOf(order.getOrderId()).equals(topUp.getOrderJson())) {
//                            order.setStatus("3");
//                            scheduledExecutorService.schedule(() -> {
//                                WebSocketUtils.sendMessage(UserConstants.SUPER_ADMIN_ID, "您有一条新的待审核订单");
//                            }, 0, TimeUnit.SECONDS);
//                            break;
//                        }
//                    }
//                }
//                Threads.sleep(1000);
//            }
//            if (num > 0) {
//                orderService.updateBatchById(StreamUtils.filter(list, order -> order.getStatus().equals("3")));
//            }
//        }
        log.info("======================更新微信订单收货信息完毕,更新数量: " + num + "======================");
    }
}
